package com.xxx.car.main;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.github.pagehelper.PageInterceptor;
import com.xxx.car.component.LoginFilter;
import com.xxx.common.push.umeng.UmengPush;
import com.xxx.common.util.IdWorker;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by youxiaojia on 2017/6/12.
 */

@Configuration
@ComponentScan(basePackages = {
        "com.xxx.car",
})
@EnableAutoConfiguration
@MapperScan(basePackages = {"com.xxx.*.mapper"})
@EnableScheduling
@EnableAsync
@EnableSwagger2
public class Application extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment environment;
    @Autowired
    private LoginFilter loginFilter;

    /**
     * 启动器
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.run(args);
        
    }


    @Bean(name = "dataSource", destroyMethod = "close", initMethod = "init")
    @ConfigurationProperties(prefix = "spring.datasource", locations = "classpath:application.properties")
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/com/xxx/car/mapper/*.xml"));
        /*LogInterceptor logInterceptor = new LogInterceptor();
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{logInterceptor});*/
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties prop = new Properties();
        prop.put("pageSizeZero", "true");
        prop.put("reasonable", "false");
        pageInterceptor.setProperties(prop);
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageInterceptor});
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public Filter characterEncodingFilter() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return characterEncodingFilter;
    }


    @Bean
    public RequestContextFilter requestContextFilter(ServletContext servletContext) {
        RequestContextFilter requestContextFilter =new RequestContextFilter();
        requestContextFilter.setServletContext(servletContext);
        requestContextFilter.setThreadContextInheritable(false);
        return requestContextFilter;
    }

    @Bean
    public ServletRegistrationBean druidServlet() {
        StatViewServlet servlet = new StatViewServlet();
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "/druid/*");
        Map<String, String> initMap = new HashMap<>();
        initMap.put("loginUsername","gaosu");
        initMap.put("loginPassword","checheche");
        servletRegistrationBean.setInitParameters(initMap);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean druidWebStatFilter() {
        FilterRegistrationBean filter = new FilterRegistrationBean();
        filter.setFilter(new WebStatFilter());
        Map<String, String> initMap = new HashMap<>();
        initMap.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,*.eot,*.svg,*.ttf,*.woff,*.woff2,/druid/*");
        filter.setInitParameters(initMap);
        filter.setUrlPatterns(Arrays.asList("/*"));

        return filter;
    }

    /**
     * 添加需要拦截的url，进行cookie检验
     * @param registry
     */

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginFilter).addPathPatterns("/admin/**");//配置登录拦截器拦截路径
    }

    @Bean
    public Docket addUserDocket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        ApiInfo apiInfo = new ApiInfo(
                "Car API Document",
                "高速项目API接口管理",
                "V1.0.0",
                "",
                "718586216@qq.com",
                "",
                "");
        docket.apiInfo(apiInfo).select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    @Bean
    public IdWorker idWorker() {
        return new IdWorker(0, 0);
    }

    @Bean
    public UmengPush umengPush() {
        return new UmengPush(environment.getProperty("umeng.appKey"), environment.getProperty("umeng.appMasterSecret"));
    }

}
